package com.wcs.exam.controller.admin.biz;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.wcs.exam.common.base.BaseBiz;
import com.wcs.exam.common.base.Result;
import com.wcs.exam.common.base.page.Page;
import com.wcs.exam.common.base.page.PageUtil;
import com.wcs.exam.common.enums.GoodsTypeEnum;
import com.wcs.exam.common.enums.OrderStatusEnum;
import com.wcs.exam.common.util.BeanUtil;
import com.wcs.exam.controller.admin.req.AdminOrderInfoChangePriceReq;
import com.wcs.exam.controller.admin.req.AdminOrderInfoEditReq;
import com.wcs.exam.controller.admin.req.AdminOrderInfoPageReq;
import com.wcs.exam.controller.admin.resp.AdminOrderInfoPageResp;
import com.wcs.exam.controller.admin.resp.AdminOrderInfoViewResp;
import com.wcs.exam.controller.biz.SysConfigCommonBiz;
import com.wcs.exam.controller.biz.resp.SysConfigPayResp;
import com.wcs.exam.dao.ExamDao;
import com.wcs.exam.dao.OrderInfoDao;
import com.wcs.exam.dao.OrderPayDao;
import com.wcs.exam.dao.impl.mapper.entity.Exam;
import com.wcs.exam.dao.impl.mapper.entity.OrderInfo;
import com.wcs.exam.dao.impl.mapper.entity.OrderPay;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Admin-订单信息
 *
 * @author wcs
 * @since 2025-03-17
 */
@Component
@RequiredArgsConstructor
public class AdminOrderInfoBiz extends BaseBiz {

    @NotNull
    private final SysConfigCommonBiz sysConfigCommonBiz;

    @NotNull
    private final OrderInfoDao dao;
    @NotNull
    private final OrderPayDao orderPayDao;
    @NotNull
    private final ExamDao examDao;

    /**
     * 订单信息-分页
     *
     * @param req 订单信息-分页查询参数
     * @return 订单信息
     */
    public Result<Page<AdminOrderInfoPageResp>> page(AdminOrderInfoPageReq req) {
        // 处理查询条件
        LambdaQueryWrapper<OrderInfo> wrapper = new LambdaQueryWrapper<OrderInfo>()
                .like(ObjectUtil.isNotEmpty(req.getOrderNo()), OrderInfo::getOrderNo, req.getOrderNo())
                .eq(StringUtils.hasText(req.getMobile()), OrderInfo::getMobile, req.getMobile())
                .eq(ObjectUtil.isNotEmpty(req.getUserId()), OrderInfo::getUserId, req.getUserId())
                .eq(ObjectUtil.isNotEmpty(req.getOrderStatus()), OrderInfo::getOrderStatus, req.getOrderStatus())
                .eq(ObjectUtil.isNotEmpty(req.getGoodsId()), OrderInfo::getGoodsId, req.getGoodsId())
                // 排序
                .orderByDesc(OrderInfo::getGmtCreate)
                .orderByDesc(OrderInfo::getId);

        // 分页查询
        IPage<OrderInfo> page = dao.page(PageDTO.of(req.getPageCurrent(), req.getPageSize()), wrapper);
        Page<AdminOrderInfoPageResp> respPage = PageUtil.transform(page, AdminOrderInfoPageResp.class);
        if (ObjectUtil.isNull(respPage) || CollectionUtil.isEmpty(respPage.getList())) {
            return Result.success(respPage);
        }


        // 获取试卷信息
        List<Long> examIds = respPage.getList().stream().filter(item -> item.getGoodsType().equals(GoodsTypeEnum.EXAM.getCode())).map(AdminOrderInfoPageResp::getGoodsId).collect(Collectors.toList());
        Map<Long, Exam> examMap = new HashMap<>();
        if (CollUtil.isNotEmpty(examIds)) {
            Collection<Exam> examList = examDao.listByIds(examIds);
            if (CollUtil.isNotEmpty(examList)) {
                examList.forEach(item -> examMap.put(item.getId(), item));
            }
        }

        // 处理分页响应信息
        for (AdminOrderInfoPageResp resp : respPage.getList()) {
            if (GoodsTypeEnum.EXAM.getCode().equals(resp.getGoodsType())) {
                Exam exam = examMap.get(resp.getGoodsId());
                if (ObjectUtil.isNotNull(exam)) {
                    resp.setGoodsExist(Boolean.TRUE);
                    resp.setExamType(exam.getExamType());
                } else {
                    resp.setGoodsExist(Boolean.FALSE);
                }
            } else {
                resp.setGoodsExist(Boolean.TRUE);
            }
        }
        return Result.success(respPage);
    }

    /**
     * 订单信息-查看
     *
     * @param id 主键ID
     * @return 订单信息
     */
    public Result<AdminOrderInfoViewResp> view(Long id) {
        OrderInfo orderInfo = dao.lambdaQuery()
                .eq(OrderInfo::getId, id)
                .one();
        if (ObjectUtil.isNull(orderInfo)) {
            return Result.error("订单信息不存在");
        }
        return Result.success(BeanUtil.copyProperties(orderInfo, AdminOrderInfoViewResp.class));
    }

    /**
     * 订单信息-编辑
     *
     * @param req 订单信息-编辑对象
     * @return 编辑结果
     */
    public Result<String> edit(AdminOrderInfoEditReq req) {
        // 获取校验订单信息
        OrderInfo orderInfo = dao.getById(req.getId());
        if (ObjectUtil.isNull(orderInfo)) {
            return Result.error("订单信息不存在");
        }

        // 更新订单信息
        OrderInfo updateOrderInfo = BeanUtil.copyProperties(req, OrderInfo.class);
        updateOrderInfo.setGmtCreate(null);
        updateOrderInfo.setGmtModified(null);
        if (dao.updateById(updateOrderInfo)) {
            return Result.success(toI18nSuccess());
        }
        return Result.error(toI18nFail());
    }

    @Transactional(rollbackFor = Exception.class)
    public Result<String> changePrice(AdminOrderInfoChangePriceReq req) {
        // 获取校验订单信息表
        OrderInfo orderInfo = dao.getById(req.getId());
        if (ObjectUtil.isNull(orderInfo)) {
            return Result.error("订单信息不存在");
        }

        // 判断状态
        if (!OrderStatusEnum.WAIT.getCode().equals(orderInfo.getOrderStatus())) {
            if (!OrderStatusEnum.SUCCESS.getCode().equals(orderInfo.getOrderStatus())) {
                return Result.error("修改订单价格状态错误");
            }
        }

        dao.lambdaUpdate()
                .eq(OrderInfo::getId, req.getId())
                .set(OrderInfo::getPaidAmount, req.getPaidAmount())
                .set(OrderInfo::getChangePrice, Boolean.TRUE)
                .update();
        if (OrderStatusEnum.SUCCESS.getCode().equals(orderInfo.getOrderStatus())) {
            orderPayDao.lambdaUpdate()
                    .eq(OrderPay::getOrderNo, orderInfo.getOrderNo())
                    .eq(OrderPay::getOrderStatus, OrderStatusEnum.SUCCESS.getCode())
                    .set(OrderPay::getPaidAmount, req.getPaidAmount())
                    .update();
        }
        return Result.success(toI18nSuccess());
    }

    /**
     * 订单信息-删除
     *
     * @param id ID主键
     * @return 删除结果
     */
    public Result<String> delete(Long id) {
        // 获取校验订单信息
        OrderInfo orderInfo = dao.lambdaQuery()
                .eq(OrderInfo::getId, id)
                .one();
        if (ObjectUtil.isNull(orderInfo)) {
            return Result.error("订单信息不存在");
        }

        // 删除订单信息
        if (dao.removeById(id)) {
            return Result.success(toI18nSuccess());
        }
        return Result.error(toI18nFail());
    }
}
